import os
import csv
from Crawler.settings import ORIGINAL


class NewWriter:
    def __init__(self):
        self.original = ORIGINAL

    def check_original(self):
        if os.path.exists(self.original):
            with open(ORIGINAL, 'r') as ori:
                records = csv.reader(ori)
                for r in records:
                    return r[0]
        else:
            with open('lottery.csv', 'w') as f:
                pass
            return None

    def write(self, arr, combcnt):
        filetp = r'lottery_comb{0}.csv'
        if os.path.exists(filetp.format(combcnt)):
            os.remove(filetp.format(combcnt))

        file = open(filetp.format(combcnt), 'a')
        for item in arr:
            file.write(item)
            file.write('\n')
        file.close()

    def write_in_start(self, content):
        with open(self.original,'r') as original_file, open('temp.csv', 'w') as temp_file:
            temp_file.write(content)
            temp_file.write(original_file.read())
            os.replace('temp.csv', self.original)
